﻿using System;
using System.Data;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using eStore.Business;
using eStore.Helpers;
using Resources;

namespace eStore.UI
{
    public partial class AdminCartDetailPage : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        protected Store store;
        protected Double timeOffset;
        protected CultureInfo currencyCulture = CultureInfo.CurrentCulture;
        protected Guid cartGuid = Guid.Empty;
        private Cart cart;
        private SiteUser cartUser;
        private bool canEdit;


        protected void Page_Load(object sender, EventArgs e)
        {
            LoadParams();

            if (!canEdit)
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            if (SiteUtils.SslIsAvailable()) SiteUtils.ForceSsl();

            LoadSettings();
            SetupCss();
            PopulateLabels();
            PopulateControls();

        }

        private void PopulateControls()
        {

            if (Page.IsPostBack) return;

            if ((store != null) && (cart != null))
            {
                lblIPAddress.Text = cart.CreatedFromIP;

                if (cartUser != null)
                {
                    lblSiteUser.Text = cartUser.Name;
                    lnkUser.Text = eStoreResources.ManageUserLink;
                    lnkUser.NavigateUrl = SiteRoot + "/Admin/ManageUsers.aspx?userid=" + cartUser.UserId.ToString(CultureInfo.InvariantCulture);
                }

                using (IDataReader reader = cart.GetItems())
                {
                    rptCartItems.DataSource = reader;
                    rptCartItems.DataBind();
                }

                litSubTotal.Text = cart.SubTotal.ToString("c", currencyCulture);

                lblCustomerAddressLine1.Text = cart.OrderInfo.CustomerAddressLine1;
                lblCustomerCity.Text = cart.OrderInfo.CustomerCity;
                lblCustomerCompany.Text = cart.OrderInfo.CustomerCompany;
                lblCustomerCountry.Text = cart.OrderInfo.CustomerCountry;
                lblCustomerEmail.Text = cart.OrderInfo.CustomerEmail;
                lblCustomerFirstName.Text = cart.OrderInfo.CustomerFirstName;
                lblCustomerPostalCode.Text = cart.OrderInfo.CustomerPostalCode;
                lblCustomerTelephoneDay.Text = cart.OrderInfo.CustomerTelephoneDay;

                Control c = Page.LoadControl("~/Controls/GCheckoutLogList.ascx");
                if (c != null)
                {
                    GCheckoutLogList googleLog = c as GCheckoutLogList;
                    if (googleLog != null)
                    {
                        googleLog.CartGuid = cart.CartGuid;
                        pnlCheckoutLog.Controls.Add(googleLog);
                    }
                }

                c = Page.LoadControl("~/Controls/PayPalLogList.ascx");
                if (c != null)
                {
                    PayPalLogList logList = c as PayPalLogList;
                    if (logList != null)
                    {
                        logList.CartGuid = cart.CartGuid;
                        pnlCheckoutLog.Controls.Add(logList);
                    }
                }

                c = Page.LoadControl("~/Controls/AuthorizeNetLogList.ascx");
                if (c != null)
                {
                    AuthorizeNetLogList logList = c as AuthorizeNetLogList;
                    if (logList != null)
                    {
                        logList.CartGuid = cart.CartGuid;
                        pnlCheckoutLog.Controls.Add(logList);
                    }
                }

                c = Page.LoadControl("~/Controls/PlugNPayLogList.ascx");
                if (c != null)
                {
                    PlugNPayLogList logList = c as PlugNPayLogList;
                    if (logList != null)
                    {
                        logList.CartGuid = cart.CartGuid;
                        pnlCheckoutLog.Controls.Add(logList);
                    }
                }
            }
        }

        void btnDelete_Click(object sender, EventArgs e)
        {
            Cart.Delete(cartGuid);

            string redirectUrl = "AdminCartBrowser.aspx?pageid="
                    + pageId.ToString(CultureInfo.InvariantCulture)
                    + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            WebUtils.SetupRedirect(this, redirectUrl);


        }


        private void PopulateLabels()
        {
            Title = SiteUtils.FormatPageTitle(siteSettings, eStoreResources.CartDetailLink);
            litHeading.Text = eStoreResources.CartDetailLink;
            
            lnkStoreMenu.Text = eStoreResources.StoreManagerHeading;
            lnkStoreMenu.NavigateUrl = SiteRoot + "/eStore/AdminDashboard.aspx?pageid="
                                       + pageId.ToString(CultureInfo.InvariantCulture)
                                       + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            lnkCartBrowser.Text = eStoreResources.BrowseCartsLink;
            lnkCartBrowser.NavigateUrl = SiteRoot + "/eStore/AdminCartBrowser.aspx?pageid="
                                       + pageId.ToString(CultureInfo.InvariantCulture)
                                       + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            lnkCurrentPage.Text = eStoreResources.CartDetailLink;
            lnkCurrentPage.NavigateUrl = Request.Url.ToString();

            btnDelete.Text = eStoreResources.AdminDeleteCartButton;

            UIHelper.AddConfirmationDialog(btnDelete, eStoreResources.AdminDeleteCartButtonWarning);

            lnkUser.Visible = WebUser.IsAdminOrContentAdminOrContentPublisher;
        }

        private void LoadSettings()
        {
            currencyCulture = ResourceHelper.GetCurrencyCulture(siteSettings.GetCurrency().Code);

            if (CurrentPage.ContainsModule(moduleId))
            {
                store = StoreHelper.GetStore();
            }

            if (store == null) { return; }

            //currencyCulture = ResourceHelper.GetCurrencyCulture(store.DefaultCurrency);

            if (cartGuid != Guid.Empty)
            {
                cart = new Cart(cartGuid);

            }

            if (cart.StoreGuid != store.Guid)
                cart = null;

            if ((cart != null) && (cart.UserGuid != Guid.Empty))
            {
                cartUser = new SiteUser(siteSettings, cart.UserGuid);
            }

            timeOffset = SiteUtils.GetUserTimeOffset();

        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", moduleId);
            cartGuid = WebUtils.ParseGuidFromQueryString("cart", cartGuid);

            canEdit = UserCanEditModule(moduleId);
        }

        protected virtual void SetupCss()
        {
            // older skins have this
            if (Page.Master == null) return;
            StyleSheet stylesheet = (StyleSheet)Page.Master.FindControl("StyleSheet");
            if (stylesheet == null) return;
            if (stylesheet.FindControl("styleestore") != null) return;
            Literal cssLink = new Literal
                                  {
                                      ID = "styleestore",
                                      Text = @"<link href='"
                                             + SiteUtils.GetSkinBaseUrl()
                                             + @"styleestore.css' type='text/css' rel='stylesheet' media='screen' />"
                                  };

            stylesheet.Controls.Add(cssLink);
        }


        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        override protected void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
            btnDelete.Click += btnDelete_Click;
            SuppressPageMenu();
        }
        #endregion
    }
}

